<template>
  <div class="tag-group-qvil">
    <div class="tag-list">
      <el-tag
        v-for="tag in displayTags"
        :key="tag.value"
        :closable="closable"
        :disabled="tag.disabled"
        :effect="effect"
        :size="size"
        :type="tag.type"
        @click="handleTagClick(tag)"
        @close="handleTagClose(tag)"
      >
        <el-icon v-if="tag.icon">
          <component :is="tag.icon" />
        </el-icon>
        {{ tag.label }}
      </el-tag>
    </div>
    <div v-if="showMore" class="tag-more">
      <el-popover placement="bottom" trigger="click" :width="200">
        <template #reference>
          <el-button link size="small" type="primary">
            更多
            <el-icon><arrow-down /></el-icon>
          </el-button>
        </template>
        <div class="tag-popover">
          <el-tag
            v-for="tag in moreTags"
            :key="tag.value"
            class="popover-tag"
            :closable="closable"
            :disabled="tag.disabled"
            :effect="effect"
            :size="size"
            :type="tag.type"
            @click="handleTagClick(tag)"
            @close="handleTagClose(tag)"
          >
            <el-icon v-if="tag.icon">
              <component :is="tag.icon" />
            </el-icon>
            {{ tag.label }}
          </el-tag>
        </div>
      </el-popover>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ArrowDown } from '@element-plus/icons-vue'
import { computed } from 'vue'
import type { TagConfig, TagGroupEvents } from './types'

const props = withDefaults(
  defineProps<{
    tags: TagConfig[]
    max?: number
    closable?: boolean
    effect?: 'dark' | 'light' | 'plain'
    size?: 'large' | 'default' | 'small'
    showAll?: boolean
    showCount?: boolean
  }>(),
  {
    max: 5,
    closable: false,
    effect: 'light',
    size: 'default',
    showAll: false,
    showCount: false,
  }
)

const emit = defineEmits<TagGroupEvents>()

// 显示标签
const displayTags = computed(() => {
  if (props.showAll) return props.tags
  return props.tags.slice(0, props.max)
})

// 更多标签
const moreTags = computed(() => {
  if (props.showAll) return []
  return props.tags.slice(props.max)
})

// 是否显示更多
const showMore = computed(() => {
  return !props.showAll && props.tags.length > props.max
})

// 处理标签点击
const handleTagClick = (tag: TagConfig) => {
  emit('tag-click', tag)
}

// 处理标签关闭
const handleTagClose = (tag: TagConfig) => {
  emit('tag-close', tag)
}
</script>

<style scoped>
.tag-group-qvil {
  display: flex;
  align-items: center;
  gap: 8px;
}
.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.tag-more {
  flex: 0 0 auto;
}
.tag-popover {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 8px;
}
.popover-tag {
  cursor: pointer;
}
</style>
